import * as shop from '../../api/shop'
import {
  SET_ITEMS,
  SET_CHECKOUT_STATUS,
  ADD_TO_CART,
  RES_PRODUCTS
} from './actionTypes'

//同步action
export const getProducts = products=>{
  return {
    type: RES_PRODUCTS,
    products
  }
}

// 异步action 函数
export const getAllProducts = ()=>{
  return dispatch => {
    shop.getAllProducts((products)=>{
      dispatch(getProducts(products))
    })
  }
};


export  const addToCart = product => {
  return {
    type: ADD_TO_CART,
    product
  }
}

export const asyncAddToCart = product => dispatch => {
//  1. 将商品库存减1
//  2. 往购物车内 的item 添加商品
  dispatch(addToCart(product))
};

export const setStatus = status => {
  return {
    type: SET_CHECKOUT_STATUS,
    status
  }
}

export const setItems = product =>{
  return {type: SET_ITEMS, product}
}

// 使用异步redux-thunk写的异步
export const checkout = products =>dispatch => {
  //1.备份购物车数据
    const productsBackups = [...products];
  //2.清空结算状态
    dispatch(setStatus(null))
  //3.清空购物车
    dispatch(setItems([]))
  //4.执行结算操作
  shop.buyProduct(products,
    ()=>dispatch(setStatus('successful')),//  成功  设置结算状态成功
    ()=>{ //  失败  设置结算状态失败,并且还原购物车状态
        dispatch(setItems(productsBackups));
        dispatch(setStatus('failed'))
    }
    )
  //  成功  设置结算状态成功
  //  失败  设置结算状态失败,并且还原购物车状态
}
